//
//  CNBBSDetailViewController.m
//  CsdnPlus
//
//  Created by 孟瑞瑞 on 2018/7/17.
//  Copyright © 2018年 CSDN. All rights reserved.
//

#import "CNBBSDetailViewController.h"
#import "CNBBSDetailCell.h"
#import "CNBBSDetailViewModel.h"
#import "CNBBSReplyListViewModel.h"
#import "CNBBSActionSheet.h" 
#import "CNBBSCreatePostViewModel.h"
#import "CNMineCollectContentModel.h"
#import "CNMineNewCollectModel.h"
#import "CNCollectSelectController.h"
#import "CNRouteTool.h"
#import <CNBaseViewTool/CNLoadingGifView.h>
#import <CNBaseViewTool/CNNoDataView.h>
#import <CNBaseViewTool/CNRefreshGifHeader.h>
#import <CNBaseViewTool/CNRefreshAutoNormalFooter.h>
#import <CNBaseViewTool/CNRefreshGifHeader.h>
#import <IQKeyboardManager/IQKeyboardManager.h>
#import <CNBaseViewTool/UIView+CNEmpty.h>
#import <CNBaseViewTool/CNShareItem.h>
#import <Masonry/Masonry.h>
#import <UMShare/UMShare.h>
#import <CNBaseViewTool/CNBottomBar.h>
#import <CNBaseViewTool/CNShareView.h>
#import <CNBaseViewTool/CNNaviTitleView.h>
#import <CNBaseViewTool/CNViewConst.h>
#import <HWPanModal/HWPanModal.h>

@interface CNBBSDetailViewController ()<UITableViewDelegate,UITableViewDataSource,CNBottomBarDelegate,CNBBSDetailCellDelegate,CNShareViewDelegate,CNActionSheetDelegate>
{
    BOOL _wasKeyboardManagerEnabled;
}

@property (nonatomic, strong) CNNaviTitleView *naviTitleView;

@property (nonatomic, strong) UILabel *naviTitleLb;

@property (nonatomic, strong) UIButton *naviMoreBtn;

@property (nonatomic, strong) UIView *tableHeadView;

@property (nonatomic, strong) UILabel *titleLabel;

@property (nonatomic, strong) UITableView *tableView;//tableView，第一个section展示内容 第二个展示回复

@property (nonatomic, strong) CNBottomBar *bootomBar;

@property (nonatomic, strong) CNBBSDetailViewModel *detailVM;

@property (nonatomic, strong) CNBBSReplyListViewModel *replyListVM;

@property (nonatomic, strong) CNLoadingGifView *loadingView;

@property (nonatomic, strong) CNNoDataView *noDataView;

@property (nonatomic, strong) CNNoDataView *noNetworkView;

@property (nonatomic, strong) CNBBSCreatePostViewModel *createVM;

@property (nonatomic, strong) CNBBSCreatePostViewModel *quoteVM;

@property (nonatomic, strong) CNBBSCreatePostViewModel *diggVM;

@property (nonatomic, strong) CNBBSCreatePostViewModel *reportVM;

@property (nonatomic, assign) BOOL isInverted;

@property (nonatomic, strong) NSMutableDictionary *cellHDic;

@end

@implementation CNBBSDetailViewController

-(NSMutableDictionary *)cellHDic
{
    if (!_cellHDic) {
        _cellHDic = [[NSMutableDictionary alloc]init];
    }
    return _cellHDic;
}

-(CNBBSDetailViewModel *)detailVM
{
    if (!_detailVM) {
        _detailVM = [[CNBBSDetailViewModel alloc]init];
    }
    return _detailVM;
}

-(CNBBSReplyListViewModel *)replyListVM
{
    if (!_replyListVM) {
        _replyListVM = [[CNBBSReplyListViewModel alloc]init];
    }
    return _replyListVM;
}

-(CNBBSCreatePostViewModel *)createVM
{
    if (!_createVM) {
        _createVM = [[CNBBSCreatePostViewModel alloc]init];
    }
    return _createVM;
}

-(CNBBSCreatePostViewModel *)quoteVM
{
    if (!_quoteVM) {
        _quoteVM = [[CNBBSCreatePostViewModel alloc]init];
    }
    return _quoteVM;
}

-(CNBBSCreatePostViewModel *)diggVM
{
    if (!_diggVM) {
        _diggVM = [[CNBBSCreatePostViewModel alloc]init];
    }
    return _diggVM;
}

-(CNBBSCreatePostViewModel *)reportVM
{
    if (!_reportVM) {
        _reportVM = [[CNBBSCreatePostViewModel alloc]init];
    }
    return _reportVM;
}

-(UILabel *)titleLabel
{
    if (!_titleLabel) {
        _titleLabel = [[UILabel alloc]init];
        _titleLabel.theme_textColor = cellTitleTextColorPicker;
        _titleLabel.font = [UIFont boldSystemFontOfSize:19];
        _titleLabel.numberOfLines = 0;
        [self.tableHeadView addSubview:_titleLabel];
        [_titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(12);
            make.left.mas_equalTo(16);
            make.right.mas_equalTo(-16);
            make.bottom.mas_equalTo(-12);
        }];
    }
    return _titleLabel;
}

-(UIView *)tableHeadView
{
    if (!_tableHeadView) {
        _tableHeadView = [[UIView alloc]init];
        _tableHeadView.theme_backgroundColor = searchPageBGColorPicker;
        // 重点,必须设置这个约束,告诉当前view的位置
        [_tableHeadView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(self.titleLabel.mas_top).offset(0);
            make.bottom.mas_equalTo(self.titleLabel.mas_bottom).offset(12);
        }];
    }
    return _tableHeadView;
}

- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView= [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsVerticalScrollIndicator = YES;
        _tableView.hidden = YES ;
        _tableView.theme_backgroundColor = searchPageBGColorPicker;
        //去掉分割线
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView registerClass:[CNBBSDetailCell class] forCellReuseIdentifier:@"bbsDetailCell"];
        _tableView.tableFooterView = [UIView new];
//        //iOS11 reloadData界面乱跳bug
        _tableView.estimatedSectionHeaderHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        _tableView.rowHeight = UITableViewAutomaticDimension;
        _tableView.estimatedRowHeight = 100;
//        _tableView.estimatedRowHeight = UITableViewAutomaticDimension;
//        _tableView.rowHeight = UITableViewAutomaticDimension;
        if(IOS11_OR_LATER){
            CNAdjustsScrollViewInsets(_tableView);
        }
        
        [self.view addSubview:_tableView];
        [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(0);
            make.left.right.mas_equalTo(0);
            make.bottom.mas_equalTo(self.bootomBar.mas_top).mas_equalTo(0);
        }];
        
        
        if (@available(iOS 11.0, *)) {
            // _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        } else {
            // Fallback on earlier versions
        };
        @weakify(self);
        _tableView.mj_header = [CNRefreshGifHeader headerWithRefreshingBlock:^{
            @strongify(self);
            [self reloadData];
        }];
        _tableView.autoHideMjFooter = YES;
        //下拉加载更多
        _tableView.mj_footer = [CNRefreshAutoNormalFooter footerWithRefreshingBlock:^{
            @strongify(self)
            [self getMoreData];
        }];
        
        _tableView.cn_emptyView = self.noDataView;
        
    }
    return _tableView;
}

-(CNBottomBar *)bootomBar
{
    if (!_bootomBar) {
        _bootomBar = [[CNBottomBar alloc]initWithBarType:(CNBottomBarTypeBBSComment)];
        _bootomBar.theme_backgroundColor = bottomBarBGColorPicker;
        _bootomBar.delegate = self;
        [self.view addSubview:_bootomBar];
        [_bootomBar mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.mas_equalTo(0);
            make.height.mas_equalTo(48);
            if (@available(iOS 11.0,*))
            {
                make.bottom.mas_equalTo(self.view.mas_safeAreaLayoutGuideBottom).mas_equalTo(0);
            }
            else
            {
                make.bottom.mas_equalTo(0);
            }
        }];
    }
    return _bootomBar;
}

- (CNLoadingGifView *)loadingView{
    if(!_loadingView){
        _loadingView = [[CNLoadingGifView alloc]init];
        [self.view addSubview:_loadingView];
        [_loadingView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.mas_equalTo(0);
        }];
    }
    return _loadingView;
}

- (CNNoDataView *)noDataView{
    if (!_noDataView) {
        _noDataView = [CNNoDataView diyEmptyView];
    }
    if ([CNThemesManager isNight])
    {
        _noDataView.imageStr = @"noData_b";
    }
    else
    {
        _noDataView.imageStr = @"noData_w";
    }
    return _noDataView;
}
- (CNNoDataView *)noNetworkView{
    if (!_noNetworkView) {
        _noNetworkView = [CNNoDataView diyEmptyActionViewWithTarget:self action:@selector(headerRefresh)];
    }
    if ([CNThemesManager isNight])
    {
        _noNetworkView.imageStr = @"noNetwork_b";
    }
    else
    {
        _noNetworkView.imageStr = @"noNetwork_w";
    }
    return _noNetworkView;
}
#pragma mark -- 初始化UI

- (void)initUI
{
    self.tableView.hidden = NO;
    [self.tableView setTableHeaderView:self.tableHeadView];
    [self.tableHeadView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(self.tableView);
    }];
    _tableView.tableHeaderView = self.tableHeadView;
    
    [self initNavBar];
}

#pragma mark - ViewDidLoad

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    self.view.theme_backgroundColor = menuPageBGColorPicker;
    self.edgesForExtendedLayout = UIRectEdgeNone;
    //禁止侧滑
    //self.fd_interactivePopDisabled = YES;
    [Factory addBlackItemToVC:self];
    [self initUI];
    [self reloadData];
    self.isInverted = NO;
//    监听登录通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refCheckCollection) name:CNLoginSuccessNotification object:nil];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    _wasKeyboardManagerEnabled = [[IQKeyboardManager sharedManager] isEnabled];
    [[IQKeyboardManager sharedManager] setEnable:NO];
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [[IQKeyboardManager sharedManager] setEnable:_wasKeyboardManagerEnabled];
}

#pragma mark -- 导航栏

- (void)initNavBar
{
    self.naviTitleView = [[CNNaviTitleView alloc]initWithFrame:CGRectMake(0, 0, kWindowW - 40, 44)];
   
    self.naviTitleLb = [[UILabel alloc]init];
    self.naviTitleLb.theme_textColor = cellTitleTextColorPicker;
    self.naviTitleLb.font = [UIFont systemFontOfSize:15];
    [_naviTitleView addSubview:_naviTitleLb];
    [_naviTitleLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(-8);
        make.centerY.mas_equalTo(0);
    }];
    self.naviTitleLb.hidden = YES;
    
    
    self.naviMoreBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
    [self.naviMoreBtn setEnlargeEdge:15];
    [_naviMoreBtn theme_setBackgroundImage:navimoreImage forState:(UIControlStateNormal)];
    [_naviMoreBtn theme_setBackgroundImage:navimoreImage forState:(UIControlStateHighlighted)];
    [_naviTitleView addSubview:_naviMoreBtn];
    [_naviMoreBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.naviTitleLb.mas_right).mas_equalTo(12);
        make.right.mas_equalTo(-10);
        make.size.mas_equalTo(CGSizeMake(24, 24));
        make.centerY.mas_equalTo(0);
    }];
    //更多
    @weakify(self);
    [_naviMoreBtn bk_addEventHandler:^(id sender) {
        @strongify(self);
        [self showBtnAction];
    } forControlEvents:(UIControlEventTouchUpInside)];
    
    self.navigationItem.titleView = self.naviTitleView;
    
}

-(void)headerRefresh
{
    [self reloadData];
}

#pragma mark  - 刷新数据

-(void)reloadData
{
    self.titleLabel.text = self.bbsTitle?:self.detailVM.title;
    self.naviTitleLb.text = [CSDNTool stringAtIndexByCount:self.bbsTitle?:self.detailVM.title withCount:35];
    dispatch_async(dispatch_get_main_queue(), ^{
        //加载视图
        [self.loadingView setHidden:self.detailVM.title];
    });
    [self.tableView cn_startLoading];
    [self.detailVM getBBSDetailWithTopicId:self.topicId  CompletionHandle:^(NSError *error) {
        if (!error) {
            if (self.detailVM.code == 200)
            {
                if (!self.bbsTitle)
                {
                    self.titleLabel.text = self.detailVM.title;
                    self.naviTitleLb.text = self.detailVM.title;
                }
                self.bootomBar.userName = self.detailVM.username;
                self.bootomBar.postId = self.detailVM.postId;
                self.bootomBar.indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
                [self.tableView reloadData];
                [self.loadingView setHidden:YES];
                self.tableView.cn_emptyView = self.noDataView;
                //刷新回复列表
                [self reloadReplyList];
                self.tableHeadView.hidden = NO;
            }
            else
            {
                [self.loadingView setHidden:YES];
                [self showErrorMsg:@"加载失败，请稍后再试"];
                
            }
            //   重置脚步 没有更多数据
            [self.tableView.mj_footer resetNoMoreData];
        }
        else
        {
            [self showError:error];;
            [self.loadingView setHidden:YES];
            self.tableView.cn_emptyView = self.noNetworkView;
            self.tableHeadView.hidden = YES;
        }
        
        [self.tableView.mj_header endRefreshing];
        
        //占位图调用时机
        [self.tableView cn_endLoading];
        //刷新是否收藏
        [self refCheckCollection];
    }];
}

#pragma mark - 刷新回复列表

-(void)reloadReplyList
{
    [self.replyListVM refreshBBSReplyListDataWithTocipId:self.topicId IsInverted:self.isInverted CompletionHandle:^(NSError *error) {
        if (!error) {
            if (self.replyListVM.code == 200)
            {
                [self.tableView reloadData];
                [self.tableView layoutIfNeeded];
            }
        }
    }];
}

-(void)getMoreData
{
    [self.tableView cn_startLoading];
    [self.replyListVM getMoreBBSReplyListDataWithTocipId:self.topicId IsInverted:self.isInverted CompletionHandle:^(NSError *error) {
        if (!error)
        {
            if (self.replyListVM.code == 200)
            {
                //AF的回调 是在主线程中
                [self.tableView reloadData];
                self.tableView.cn_emptyView = self.noDataView;
            }
            if ([self.replyListVM isHasMore])
            {
                [self.tableView.mj_footer endRefreshing];
            }
            else
            {
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
            }
        }
        else{
            [self showError:error];;
            [self.tableView.mj_footer endRefreshing];
            self.tableView.cn_emptyView = self.noNetworkView;
        }
        //占位图调用时机
        [self.tableView cn_endLoading];
    }];
}

#pragma mark - 点击更多按钮

-(void)showBtnAction
{
    NSArray *array = @[@"倒序"];
    if (self.isInverted)
    {
        array = @[@"正序"];
    }
   
    CNBBSActionSheet *sheet = [[CNBBSActionSheet alloc]initWithTitleArray:array andShowCancel:YES];
    sheet.tag = 1000;
    sheet.delegate = self;
    [self.view.window addSubview:sheet];
}

#pragma mark - 分享视图

- (void)shareNews
{
    CNShareView *view = [CNShareView new];
    view.syncBlinBtn.hidden = YES;
    view.shareInfos = [self createShareItems];
    view.frame = [[UIScreen mainScreen]bounds];
    view.delegate = self ;
    [[UIApplication sharedApplication].keyWindow addSubview:view];
    [view showShareView];
}

#pragma mark -- 创建更多视图的item

- (NSArray<NSArray<CNShareItem *> *> *)createShareItems{
    CNShareItem *itemWX = [[CNShareItem alloc]initWithShareType:CNShareTypeWXFriend iconImagePicker:shareWeixinImage title:@"微信"];
    CNShareItem *itemTime = [[CNShareItem alloc]initWithShareType:CNShareTypeWXTimesmp iconImagePicker:sharePengyouquanImage title:@"朋友圈"];
    CNShareItem *itemWeiBo = [[CNShareItem alloc]initWithShareType:CNShareTypeWeiBo iconImagePicker:shareWeiboImage title:@"微博"];
    CNShareItem *itemQQ = [[CNShareItem alloc]initWithShareType:CNShareTypeQQ iconImagePicker:shareQQImage title:@"QQ"];
    CNShareItem *itemQZone = [[CNShareItem alloc]initWithShareType:CNShareTypeQZone iconImagePicker:shareQzoneImage title:@"QZone"];
    CNShareItem *itemSys = [[CNShareItem alloc] initWithShareType:CNShareTypeSysShare iconImagePicker:shareMoreImage title:@"更多"];
    //    CNShareItem *itemSys = [[CNShareItem alloc]initWithShareType:CNShareTypeSysShare iconImageName:@"bespoke_editLive_n" title:@"系统分享"];
    CNShareItem *itemCopyLink = [[CNShareItem alloc]initWithShareType:CNShareTypeCopyLink iconImagePicker:shareLianjieImage title:@"复制链接"];
    CNShareItem *itemDingDing = [[CNShareItem alloc]initWithShareType:CNShareTypeDingDing iconImagePicker:shareDingdingImage title:@"钉钉"];
    
    NSArray *array1 =@[itemWX,itemTime,itemWeiBo,itemQQ,itemQZone];
    NSArray *array2 =@[itemDingDing,itemCopyLink,itemSys];
    
    return @[array1,array2];
}

#pragma mark -- CNShareViewDelegate

- (void)shareWithType:(CNShareType)shareType
{
    switch (shareType) {
        case CNShareTypeSysShare:
        {
            NSString *shareText = self.detailVM.title;
            UIImage *shareImage = [UIImage imageNamed:@"shareIcon"];
            NSURL *shareURL = [NSURL URLWithString:self.detailVM.url];
            NSArray *activityItems = [[NSArray alloc] initWithObjects:shareText, shareImage, shareURL, nil];
            
            UIActivityViewController *vc = [[UIActivityViewController alloc] initWithActivityItems:activityItems applicationActivities:nil];
            vc.popoverPresentationController.sourceView = self.view;
            UIActivityViewControllerCompletionWithItemsHandler myBlock = ^(UIActivityType activityType, BOOL completed, NSArray *returnedItems, NSError *activityError) {
                DDLogDebug(@"%@",activityType);
                if (completed) {
                    DDLogDebug(@"分享成功");
                } else {
                    DDLogDebug(@"分享失败");
                }
                [vc dismissViewControllerAnimated:YES completion:nil];
            };
            
            vc.completionWithItemsHandler = myBlock;
            
            [self.navigationController presentViewController:vc animated:YES completion:nil];
            
            //点击全部分享 - 点击统计
        }
            break;
        case CNShareTypeWXFriend:
        {
            if ([[UMSocialManager  defaultManager] isInstall:UMSocialPlatformType_WechatSession])
            {
                [self shareWebPageToPlatformType:UMSocialPlatformType_WechatSession];
                //分享帖子_微信 - 点击统计
            }
            else
            {
                [self showErrorMsgDescription:@"您未安装微信"];
            }
        }
            break;
        case CNShareTypeWXTimesmp:
        {
            if ([[UMSocialManager  defaultManager] isInstall:UMSocialPlatformType_WechatTimeLine])
            {
                [self shareWebPageToPlatformType:UMSocialPlatformType_WechatTimeLine];
                //分享帖子_朋友圈 - 点击统计
            }
            else
            {
                [self showErrorMsgDescription:@"您未安装微信"];
            }
            
        }
            break;
        case CNShareTypeWeiBo:
        {
            if ([[UMSocialManager  defaultManager] isInstall:UMSocialPlatformType_Sina])
            {
                [self shareWebPageToPlatformType:UMSocialPlatformType_Sina];
                //分享帖子_朋友圈 - 点击统计
            }
            else
            {
                [self showErrorMsgDescription:@"您未安装微博"];
            }
        }
            break;
        case CNShareTypeQQ:
        {
            if ([[UMSocialManager  defaultManager] isInstall:UMSocialPlatformType_QQ])
            {
                [self shareWebPageToPlatformType:UMSocialPlatformType_QQ];
                //分享帖子_朋友圈 - 点击统计
            }
            else
            {
                [self showErrorMsgDescription:@"您未安装QQ"];
            }
            
        }
            break;
        case CNShareTypeQZone:
        {
            if ([[UMSocialManager  defaultManager] isInstall:UMSocialPlatformType_Qzone])
            {
                [self shareWebPageToPlatformType:UMSocialPlatformType_Qzone];
                //分享帖子_朋友圈 - 点击统计
            }
            else
            {
                [self showErrorMsgDescription:@"您未安装QQ"];
            }
        }
            break;
        case CNShareTypeCopyLink:
        {
            NSString * _description= [NSString stringWithFormat:@"我用#CSDN#这个app发现了有技术含量的博客，小伙伴们求同去《%@》, 一起来围观吧 %@",self.detailVM.title,self.detailVM.url];
            
            UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
            NSString *text = _description;
            [pasteboard setString:text];
            if ([pasteboard.string isEqualToString:text])
            {
                [self showSuccessMsg:@"复制成功"];
                //分享帖子_复制链接 - 点击统计
            }
            else
            {
                [self showErrorMsgDescription:@"复制失败"];
            }
        }
            break;
        case CNShareTypeDingDing:
        {
            if ([[UMSocialManager  defaultManager] isInstall:UMSocialPlatformType_DingDing])
            {
                [self shareWebPageToPlatformType:UMSocialPlatformType_DingDing];
                //分享帖子_钉钉 - 点击统计
            }
            else
            {
                [self showErrorMsgDescription:@"您未安装钉钉"];
            }
        }
            break;
        default:
            break;
    }
}

- (void)shareWebPageToPlatformType:(UMSocialPlatformType)platformType
{
    
    //创建分享消息对象
    UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
    if (platformType == UMSocialPlatformType_Sina) {
        messageObject.title = self.detailVM.title;
        messageObject.text = [NSString stringWithFormat:@"推荐CSDN作者：%@ (@%@) 的帖子 《%@》%@ (下载 @CSDN App,创作你的帖子 https://www.csdn.net/apps/download)",self.detailVM.nickname,self.detailVM.nickname,self.detailVM.title,self.detailVM.url];
    }else{
        //创建网页内容对象
        UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:self.detailVM.title descr:self.detailVM.desc thumImage:[UIImage imageNamed:@"shareIcon"]];
        //设置网页地址
        shareObject.webpageUrl = self.detailVM.url;
        
        //分享消息对象设置分享内容对象
        messageObject.shareObject = shareObject;
    }
    
    //调用分享接口
    [[UMSocialManager defaultManager] shareToPlatform:platformType messageObject:messageObject currentViewController:self completion:^(id data, NSError *error) {
        if (error) {
            UMSocialLogInfo(@"************Share fail with error %@*********",error);
            [self  showErrorMsgDescription:@"分享失败"];
        }else{
            if ([data isKindOfClass:[UMSocialShareResponse class]]) {
                UMSocialShareResponse *resp = data;
                //分享结果消息
                UMSocialLogInfo(@"response message is %@",resp.message);
                //第三方原始返回的数据
                UMSocialLogInfo(@"response originalResponse data is %@",resp.originalResponse);
                [self showSuccessMsg:@"分享成功"];
                
            }else{
                UMSocialLogInfo(@"response data is %@",data);
            }
        }
    }];
    
}

#pragma mark -- UIScrollViewDelegate

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat offsetY = scrollView.contentOffset.y;
    if(offsetY >= self.tableHeadView.height)
    {
        self.navigationItem.titleView = self.naviTitleView;
        self.naviTitleLb.hidden = NO;
    }
    else
    {
        self.naviTitleLb.hidden = YES;
    }
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return self.detailVM.text_body != nil ?1:0;
    }
    return self.replyListVM.rowNumber;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    CNBBSDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:@"bbsDetailCell" forIndexPath:indexPath];
    
//    NSString *CellIdentifier = [NSString stringWithFormat:@"Cell%ld%ld", [indexPath section], [indexPath row]];
//    CNBBSDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
//    if (!cell) {
//        cell = [[CNBBSDetailCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
//    }
    
   
    [self configureCell:cell atIndexPath:indexPath];
    
    return cell;
}


// save height
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    [self.cellHDic setObject:@(cell.frame.size.height) forKey:indexPath];
}

//解决reload时 TableView 抖动问题
// give exact height value
- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSNumber *height = [self.cellHDic objectForKey:indexPath];
    if (height) return height.doubleValue;
    return UITableViewAutomaticDimension;
}

- (void)configureCell:(CNBBSDetailCell *)cell atIndexPath:(NSIndexPath *)indexPath
{
    //    cell.fd_enforceFrameLayout = NO; // Enable to use "-sizeThatFits:"
    cell.delegate = self;
    if (indexPath.section == 0)
    {
        cell.htmlText = self.detailVM.text_body;
        cell.headUrl = self.detailVM.avatar;
        cell.nickName = self.detailVM.nickname;
        cell.isScore = YES;
        cell.score = [NSString stringWithFormat:@"%@分",self.detailVM.score];
        cell.floorText = @"楼主";
        cell.timeText = self.detailVM.created_at;
        cell.isDigg = self.detailVM.is_digged;
        cell.diggCount = self.detailVM.digg_count;
    }
    else
    {
        cell.htmlText = [self.replyListVM bodyForRow:indexPath.row];
        cell.headUrl = [self.replyListVM avatarForRow:indexPath.row];
        cell.nickName = [self.replyListVM nickNameForRow:indexPath.row];
        cell.isScore = NO;
        cell.floorText = [NSString stringWithFormat:@"%@楼",[self.replyListVM floorForRow:indexPath.row]];
        cell.timeText = [self.replyListVM createdAtForRow:indexPath.row];
        cell.isDigg = [self.replyListVM isDiggedForRow:indexPath.row];
        cell.diggCount = [self.replyListVM diggForRow:indexPath.row];
    }
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
}

-(void)clickInformWithTag:(NSInteger)tag
{
    NSArray *array = @[@"跑题",@"骂人",@"灌水",@"倒分",@"刷屏",@"招聘",@"广告",@"政治",@"色情",@"其他"];
    CNBBSActionSheet *sheet = [[CNBBSActionSheet alloc]initWithTitleArray:array andShowCancel:YES];
    sheet.tag = tag;
    sheet.delegate = self;
    [self.view.window addSubview:sheet];
}

#pragma mark - CNBBSDetailCellDelegate

/// 点击了 头像
- (void)cellDidClickHeadImage:(CNBBSDetailCell *)cell
{
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    NSString *userName = @"";
    if (indexPath.section == 0)
    {
        userName = self.detailVM.username;
    }
    else
    {
        userName = [self.replyListVM userNameForRow:indexPath.row];
    }
    [CNRouteTool routeUrl:[CNRoutePath appUrlWithRoutePath:CNHisPageRoute] navigationVc:self.navigationController refer:@"" trackingCode:@"" urlParams:@{} vipReferrer:@"" exts:@{}];
}
/// 点击了回复
- (void)cellDidClickReplyButton:(CNBBSDetailCell *)cell
{
   
    if ([CNViewConst canEidtorAction]) {
         NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
         NSString *placeString = @"";
         if (indexPath.section == 0)
         {
             self.bootomBar.userName = self.detailVM.username;
             self.bootomBar.postId = self.detailVM.postId;
             self.bootomBar.indexPath = indexPath;
             placeString = @"想对楼主说点什么…";
             //点击回复楼主 - 点击统计
         }
         else
         {
             self.bootomBar.userName = [self.replyListVM userNameForRow:indexPath.row];
             self.bootomBar.postId = [self.replyListVM postIdRow:indexPath.row];
             self.bootomBar.indexPath = indexPath;
             placeString = [NSString stringWithFormat:@"引用 %@ 楼 %@ 的回复：",[self.replyListVM floorForRow:indexPath.row],[self.replyListVM nickNameForRow:indexPath.row]];
             //点击楼层回复 - 点击统计
         }
         
         [self.bootomBar showKeyboardViewWithText:placeString];
    }else{
        id action = [CNViewConst getActionVC];
        if ([action isKindOfClass:[NSString class]]) {
            [CNViewConst showErrorMsg:action];
        }else if ([action isKindOfClass:[UIViewController class]]){
            [self.navigationController pushViewController:action animated:YES];
        }
    }
}
/// 点击了 顶
- (void)cellDidClickDiggButton:(CNBBSDetailCell *)cell
{
    if (![CNViewConst isLogin]){
     [CNRouteTool routeUrl:[CNRoutePath appUrlWithRoutePath:CNLoginQuickRoute] navigationVc:self.navigationController refer:@"" trackingCode:@"" urlParams:@{} vipReferrer:@"" exts:@{}];
    }else{
        NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
        //点赞
        if (indexPath.section == 0)
        {
            [self diggWithTopicId:self.topicId PostId:self.detailVM.postId IsTopic:YES IndexPath:indexPath];
            //帖子楼主点赞 - 点击统计
        }
        else
        {
            [self diggWithTopicId:self.topicId PostId:[self.replyListVM postIdRow:indexPath.row] IsTopic:NO IndexPath:indexPath];
            //帖子回复点赞 - 点击统计
        }
    }
}

#pragma mark - 点击分享按钮
-(void)didClickShareBtn
{
    [self shareNews];
}

#pragma mark - 点击收藏按钮
//点击了收藏
-(void)didClickCollectionBtn
{
    if ([CNViewConst isLogin])
        {

            CNMineNewCollectModel *collectModel = [[CNMineNewCollectModel alloc] init];
            collectModel.SourceID = self.topicId;
            collectModel.Author = self.detailVM.username;
            collectModel.Source = @"bbs";
            
            CNMineCollectContentModel *contentModel = [[CNMineCollectContentModel alloc] init];
            contentModel.title = self.detailVM.title;
            contentModel.url =self.detailVM.url;
            contentModel.desc = self.detailVM.desc;
            collectModel.content = contentModel;
            
            
            CNCollectSelectController *selectVC = [[CNCollectSelectController alloc] initWithCollectModel:collectModel];
            selectVC.fromViewController = self;
            [self presentPanModal:selectVC];

            selectVC.favoriteResultBlock = ^(BOOL success, BOOL isFavorited,NSString *errorMessage) {
                if (isFavorited) {
                    if (success) {
                        [self refCheckCollection];
                        self.bootomBar.isCollection = YES;
                        [CSDNTool showAlert:@"已收藏" inView:nil];
                        //点击收藏帖子 - 点击统计
                        
                    }else{
                        [CSDNTool showAlert:errorMessage inView:nil];
                        
                    }
                }else{
                    if (success) {
                        [self refCheckCollection];
                        self.bootomBar.isCollection = NO;
                        [CSDNTool showAlert:@"取消收藏" inView:nil];
                    }else{
                        [CSDNTool showAlert:errorMessage inView:nil];

                    }
                   
                }
               
            };
        }
        else
        {
            [CNRouteTool routeUrl:[CNRoutePath appUrlWithRoutePath:CNLoginQuickRoute] navigationVc:self.navigationController refer:@"" trackingCode:@"" urlParams:@{} vipReferrer:@"" exts:@{}];
        }
}

#pragma mark - 查询是否收藏
-(void)refCheckCollection
{
    if ([CNViewConst isLoginUserName:self.detailVM.username])
    {
        self.bootomBar.isMe = YES;
        return;
    }
    else
    {
        self.bootomBar.isMe = NO;
    }
    
    [self.detailVM getCheckCollectionWithUrl:self.detailVM.url CompletionHandle:^(NSError *error) {
        if (!error) {
            if (self.detailVM.code == 200)
            {
                self.bootomBar.isCollection = self.detailVM.is_Fav;
            }
            
        }
    }];
}

-(void)cellDidClickReportButton:(CNBBSDetailCell *)cell
{
    if (![CNViewConst isLogin])
    {
        [CNRouteTool routeUrl:[CNRoutePath appUrlWithRoutePath:CNLoginQuickRoute] navigationVc:self.navigationController refer:@"" trackingCode:@"" urlParams:@{} vipReferrer:@"" exts:@{}];

        return;
    }
    {
        NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
        if (indexPath.section == 0)
        {
            if (![CNViewConst isLoginUserName:self.detailVM.username])
            {
                [self clickInformWithTag:indexPath.row + 2000];
            }
            else
            {
                [CSDNTool showAlert:@"不能举报自己" inView:self.view];
            }
        }
        else
        {
            if (![CNViewConst isLoginUserName:[self.replyListVM userNameForRow:indexPath.row]])
            {
                [self clickInformWithTag:indexPath.row + 3000];
            }
            else
            {
                [CSDNTool showAlert:@"不能举报自己" inView:self.view];
            }
        }
    }
}

-(void)cellDidClickShieldButton:(CNBBSDetailCell *)cell
{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"是否确认要屏蔽" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    UIAlertAction *deleteAction = [UIAlertAction actionWithTitle:@"确认屏蔽" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
        if (indexPath.section == 0)
        {
            self.detailVM.text_body = nil;
            [self.tableView reloadData];
        }
        else
        {
            [self.replyListVM.dataArr removeObjectAtIndex:indexPath.row];
            // 刷新
            [self.tableView reloadData];
        }
    }];
    [alert addAction:cancelAction];
    [alert addAction:deleteAction];
    [self presentViewController:alert animated:YES completion:nil];
}

#pragma mark - 点赞请求

-(void)diggWithTopicId:(NSString *)topicId PostId:(NSString *)postId IsTopic:(BOOL)isTopic IndexPath:(NSIndexPath *)indexPath
{
    [self.diggVM getBBSDiggWithTopicId:topicId PostId:postId IsTopic:isTopic CompletionHandle:^(NSError *error) {
        if (!error)
        {
            if (self.diggVM.code == 200)
            {
                if (indexPath.section == 0)
                {
                    if (self.detailVM.is_digged)
                    {
                        //取消赞
                        self.detailVM.digg_count = [NSString stringWithFormat:@"%ld",([self.detailVM.digg_count integerValue] - 1)];
                    }
                    else
                    {
                        //点赞
                        self.detailVM.digg_count = [NSString stringWithFormat:@"%ld",([self.detailVM.digg_count integerValue] + 1)];
                    }
                    self.detailVM.is_digged = !self.detailVM.is_digged;
                    
                    [self.tableView reloadData];
                }
                else
                {
                    if ([self.replyListVM isDiggedForRow:indexPath.row])
                    {
                        //取消赞
                        [self.replyListVM setDigg:[NSString stringWithFormat:@"%ld",([[self.replyListVM diggForRow:indexPath.row] integerValue] - 1)] ForRow:indexPath.row];
                    }
                    else
                    {
                        //点赞
                        [self.replyListVM setDigg:[NSString stringWithFormat:@"%ld",([[self.replyListVM diggForRow:indexPath.row] integerValue] + 1)] ForRow:indexPath.row];
                    }
                    [self.replyListVM setIsDigged:![self.replyListVM isDiggedForRow:indexPath.row] ForRow:indexPath.row];
                    [self.tableView reloadData];
                }
            }
        }
    }];
}

#pragma mark - CNBottomBarDelegate
//点击评论框
-(void)didClickCommentTextView
{
    if (![CNViewConst isLogin]){
        [CNRouteTool routeUrl:[CNRoutePath appUrlWithRoutePath:CNLoginQuickRoute] navigationVc:self.navigationController refer:@"" trackingCode:@"" urlParams:@{} vipReferrer:@"" exts:@{}];
    }
    else
    {
        if ([CNViewConst canEidtorAction]) {
              self.bootomBar.userName = self.detailVM.username;
                 self.bootomBar.postId = self.detailVM.postId;
                 self.bootomBar.indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
                 [self.bootomBar.toolBar showKeyBoard];
                 //点击回复楼主 - 点击统计
        }else{
            id action = [CNViewConst getActionVC];
            if ([action isKindOfClass:[NSString class]]) {
                [CNViewConst showErrorMsg:action];
            }else if ([action isKindOfClass:[UIViewController class]]){
                [self.navigationController pushViewController:action animated:YES];
            }
        }
    }
}

//点击发送
- (void)sendCommentWidthText:(NSString *)text PostId:(NSString *)postId IndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0)
    {
        [self createPostWithTopicId:self.topicId Body:[PPStickerDataManager changeStringWithUrl:text]];
        //成功回复楼主 - 点击统计
    }
    else if (indexPath.section == 1)
    {
        [self.quoteVM getBBSQuoteWithPostId:postId CompletionHandle:^(NSError *error) {
            if (!error) {
                if (self.quoteVM.code == 200)
                {
                    NSString *frontStr = [NSString stringWithFormat:@"[quote=%@]",[NSString stringWithFormat:@"引用 %@ 楼 %@ 的回复：",[self.replyListVM floorForRow:indexPath.row],[self.replyListVM nickNameForRow:indexPath.row]]];
                    frontStr = [[frontStr stringByAppendingString:self.quoteVM.body?:@""] stringByAppendingString:@"[/quote]"];
                    
                    frontStr = [frontStr stringByAppendingString:[PPStickerDataManager changeStringWithUrl:text]];
                    [self createPostWithTopicId:self.topicId Body:frontStr];
                }
            }
        }];
    }
}

#pragma mark 回帖请求

-(void)createPostWithTopicId:(NSString *)topicId Body:(NSString *)body
{
    [self.createVM getBBSCreatePostWithTopicId:topicId Body:body CompletionHandle:^(NSError *error) {
        if (!error)
        {
            if (self.createVM.code == 200 && (!self.createVM.errorStr || !self.createVM.message))
            {
                //必须向tableView的数据源数组中相应的添加一条数据
                CNBBSReplyListDataModel *replyDataModel = [[CNBBSReplyListDataModel alloc]init];
                replyDataModel.nickname = self.createVM.nickname;
                replyDataModel.digg = self.createVM.digg;
                replyDataModel.is_digged = self.createVM.is_digged;
                replyDataModel.body = self.createVM.body;
                replyDataModel.avatar = self.createVM.avatar;
                replyDataModel.created_at = self.createVM.created_at;
                replyDataModel.username = self.createVM.username;
                replyDataModel.post_id = self.createVM.postId;
                replyDataModel.floor = self.createVM.floor;
                
                if (!self.isInverted)//正序
                {
                     if (self.replyListVM.rowNumber % 10 || self.replyListVM.rowNumber == 0)
                     {
                         NSMutableArray *indexPaths = [[NSMutableArray alloc] init];
                         NSInteger row = self.replyListVM.rowNumber;
                         NSIndexPath *indexPath = [NSIndexPath indexPathForRow:row inSection:1];
                         [indexPaths addObject: indexPath];
                         //[self.tableView beginUpdates];
                         [self.replyListVM.dataArr addObject:replyDataModel];
                         [self.tableView insertRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationNone];
                         //[self.tableView endUpdates];
                         [self.tableView reloadData];
                         [self tableView:self.tableView scrollTableToFoot:YES];
                     }
                }
                else
                {
                    NSMutableArray *indexPaths = [[NSMutableArray alloc] init];
                    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:1];
                    [indexPaths addObject: indexPath];
                    //[self.tableView beginUpdates];
                    [self.replyListVM.dataArr insertObject:replyDataModel atIndex:0];
                    [self.tableView insertRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationNone];
                    //[self.tableView endUpdates];
                    [self.tableView reloadData];
                }
                [self showSuccessMsg:@"回帖成功"];
            }
            else if (self.createVM.code == 401)
            {
                //未登录
                [CNRouteTool routeUrl:[CNRoutePath appUrlWithRoutePath:CNLoginQuickRoute] navigationVc:self.navigationController refer:@"" trackingCode:@"" urlParams:@{} vipReferrer:@"" exts:@{}];
            }
            else
            {
                [self showErrorMsgDescription:self.createVM.message?:@"回帖失败"];
            }
        }
        else
        {
            [self showErrorMsgDescription:@"回帖失败"];
        }
    }];
}

#pragma mark - 滚动至最后一行
- (void)tableView:(UITableView *)tableView scrollTableToFoot:(BOOL)animated
{
    NSInteger s = [tableView numberOfSections];  /** 有多少组 */
    if (s<1) return;  /** 无数据时不执行 要不会crash */
    NSInteger r = [tableView numberOfRowsInSection:s-1]; /* 最后一组有多少行 */
    if (r<1) return;
    NSIndexPath *ip = [NSIndexPath indexPathForRow:r-1 inSection:s-1];  /** 取最后一行数据 */
    [tableView scrollToRowAtIndexPath:ip atScrollPosition:UITableViewScrollPositionBottom animated:animated]; /** 滚动到最后一行 */
}

#pragma mark - CNActionSheetDelegate
- (void)actionSheet:(CNBBSActionSheet *)actionSheet clickButtonAtIndex:(NSInteger)buttonIndex
{
    if (actionSheet.tag == 1000)
    {
        if (buttonIndex == 1)
        {
            self.isInverted = !self.isInverted;
            //刷新回复列表
            [self reloadReplyList];
        }
    }
    else
    {
        if (buttonIndex == 11)
        {
            return;
        }
        NSArray *reasonArray = @[@"假数据占位",@"9",@"8",@"7",@"6",@"5",@"4",@"3",@"2",@"1",@"0"];
        NSString *reasonType = reasonArray[buttonIndex];
    
        if (actionSheet.tag >= 2000 && actionSheet.tag < 3000)
        {
            [self reportWithTopicId:self.topicId PostId:self.detailVM.postId IsTopic:YES ReasonType:reasonType];
        }
        else
        {
            [self reportWithTopicId:self.topicId PostId:[self.replyListVM postIdRow:(actionSheet.tag - 3000)] IsTopic:NO ReasonType:reasonType];
        }
    }
    
}

#pragma mark - 举报请求

-(void)reportWithTopicId:(NSString *)topicId PostId:(NSString *)postId IsTopic:(BOOL)isTopic ReasonType:(NSString *)reasonType
{
    [self.reportVM getBBSReportWithTopicId:topicId PostId:postId IsTopic:isTopic ReasonType:reasonType CompletionHandle:^(NSError *error) {
        if (!error) {
            if (self.reportVM.code == 200)
            {
                if (self.reportVM.success)
                {
                    [self showSuccessMsg:self.reportVM.message];
                }
                else
                {
                    if ([self.reportVM.message containsString:@"该回复已有用户举报"])
                    {
                        [self showErrorMsgDescription:@"您已经成功举报，请等待审核"];
                    }
                    else
                    {
                        [self showErrorMsgDescription:self.reportVM.message];
                    }
                }
            }
            else
            {
                
                [self showErrorMsg:@"举报失败"];
            }
        }
        else
        {
            [self showErrorMsgDescription:@"举报失败"];
        }
    }];
}

#pragma mark - dealloc
-(void)dealloc
{
    //在页面消失的回调方法中移除通知。
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end
